<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

use app\index\model\Nav;
use app\index\model\KnowUser;
use app\index\model\KnowUserVip;
use app\index\service\VipService;
use app\common\service\SessionUser;
use app\atxunda\model\AdminTraining;



// 应用公共文件
error_reporting(E_ERROR | E_WARNING | E_PARSE);
if( !function_exists("user") ){
/**
 * 随机验证码
 */
    function user ()
    {
    	return SessionUser::user();
    }
}

if(!function_exists('uris')){
    /**
     * 域名
     */
    function uris ($str = '')
    {
        return 'http://www.atxunda.com';
    }
}

function returnUserDispose($userId){
    $identity = '普通用户';
    $vips = VipService::disposeUserVip($userId);
    if ($vips){
        if ( $vips[1]){
            $identity = '超级会员';
        }else{
            if ($vips[2]){
                $navData = Nav::getAllDataIds(['nav_id'=>array_keys($vips[2])], 'nav_name');
                $identity = implode('<br/>',$navData).'会员';
            }
        }
    }
    return $identity;
}

function returnUserExpireDispose($userId){
    $time = '';
    $vips = VipService::disposeUserVip($userId);
    if ($vips){
        if ( $vips[1]){
            $times = array_column($vips[1], 'expired_time');
            $time = implode('<br/>',$times);
        }else{
            if ($vips[2]){
                $times = array_column($vips[2], 'expired_time');
                $time = implode('<br/>',$times);
            }
        }
    }
    return $time;
}


function checkNickname($name){
    if(preg_match('/^1[3456789]\d{9}$/', $name)) $name = substr_replace($name, '****', 3, 4);
    if (strpos($name, '@')) {
        $email_array = explode("@", $name);
        $prevfix = (strlen($email_array[0]) < 4) ? "" : substr($name, 0, 3); //邮箱前缀
        $count = 0;
        $name = preg_replace('/([\d\w+_-]{0,100})@/', '***@', $name, -1, $count);
        $name = $prevfix . $name;
    }
    return $name;
}

function disposeStrP($content){
    $str = str_replace("\n", "<br/>", $content);
    return $str;
}

function Sec2Time($time){  
    if(is_numeric($time)){  
        $value = array(  
            "hours" => 0, "minutes" => 0, "seconds" => 0,  
        );
        $t = '';
        // if($time >= 3600){  
            $value["hours"] = floor($time/3600);  
            $t .= ($value["hours"] ?: '00').':';
            $time = ($time%3600);
        // }
        // if($time >= 60){  
            $value["minutes"] = floor($time/60);
            $t .= ($value["minutes"] ? ($value["minutes"] > 10 ? $value["minutes"] : '0'.$value['minutes']) : '00') .':';
            $time = ($time%60);  
        // }  
        $value["seconds"] = round($time,2);  
        $t .= $value["seconds"] > 10 ? $value["seconds"] : '0'.$value['seconds'];
        Return $t;  

    }else{  
        return (bool) FALSE;  
    }  
} 

function returnUserName($userId)
{
    if ($userId == 0) return '迅达学院';
    $userData = KnowUser::getUserOneIds($userId);
    return $userData['know_nickname'] ?: checkNickname($userData['know_phone']);
}


function returnUserAvatar($userId)
{
    if ($userId == 0) return '/public/img/user1.jpg';
    $userData = KnowUser::getUserOneIds($userId);
    return $userData['know_avatar'];
}


function returnAdminTrain($id)
{
    $data = AdminTraining::getUserData($id, 'content');
    return $data['content'] ?: '';
}

function get_client_ip() {
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
    	$ipaddress = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    	$ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
    	$ipaddress = $_SERVER['REMOTE_ADDR'];
    }
    return $ipaddress;
}


/**
* [rand_num 获取随机数]
* @return [type] [description]
*/
function rand_num(){
    $num="";
    for($i=0;$i<6;$i++){
        $num .= rand(0,9);
    }
    return $num;
}


function encrypts($data, $key)  
{  
    $key    =   md5($key);  
    $x      =   0;  
    $len    =   strlen($data);  
    $l      =   strlen($key);  
    for ($i = 0; $i < $len; $i++)  
    {  
        if ($x == $l)   
        {  
            $x = 0;  
        }  
        $char .= $key[$x];  
        $x++;  
    }  
    for ($i = 0; $i < $len; $i++)  
    {  
        $str .= chr(ord($data[$i]) + (ord($char[$i])) % 256);  
    }  
    return base64_encode($str);  
}


function decrypts($data, $key)  
{  
    $key = md5($key);  
    $x = 0;  
    $data = base64_decode($data);  
    $len = strlen($data);  
    $l = strlen($key);  
    for ($i = 0; $i < $len; $i++)  
    {  
        if ($x == $l)   
        {  
            $x = 0;  
        }  
        $char .= substr($key, $x, 1);  
        $x++;  
    }  
    for ($i = 0; $i < $len; $i++)  
    {  
        if (ord(substr($data, $i, 1)) < ord(substr($char, $i, 1)))  
        {  
            $str .= chr((ord(substr($data, $i, 1)) + 256) - ord(substr($char, $i, 1)));  
        }  
        else  
        {  
            $str .= chr(ord(substr($data, $i, 1)) - ord(substr($char, $i, 1)));  
        }  
    }  
    return $str;  
}  


function checkNicknameRight($name){
    if(preg_match('/^1[3456789]\d{9}$/', $name) || strpos($name, '@')){
        return true;
    }else{
        return false;
    }
}

 if( !function_exists("ccTHQS") ){
        /**
         * 将参数拼接为url: key=value&key=value
         * @param   $params
         * @return  string
         */
        function ccTHQS( $data, $uris ){
            ksort($data);
            $sign = '';
            foreach ($data as $key => $val) {
                $sign .= $key . '=' . urlencode($val) . '&';
            }
            $sign .= 'time='.time();
            $salt = $sign.'&salt=SexXFIDnvcWf0oXvrLp3LlsGjCHQA8DX';
            $hash = md5($salt);
            $data = $sign. '&hash='. $hash;
            $result = file_get_contents($uris. '?'.$data);
            try{
                $result = file_get_contents($uris. '?'.$data);
                $result = json_decode($result,true);
                return [$result,'OK',''];
            } catch(\Exception $e){
                return [[],'FAIL',''];
            }
        }
    }

function isBase64($value) {
    $value = substr($value,-1);
    if ($value == '='){
        return true;
    } else {
        return false;
    }
}

function random($length, $chars = '123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ') {
    $hash = '';
    $max = strlen($chars) - 1;
    for($i = 0; $i < $length; $i++) {
        $hash .= $chars[mt_rand(0, $max)];
    }
    return $hash;
}

function getLoginToken(){
    $charid = strtoupper(md5(uniqid(mt_rand(), true)));
    return substr($charid, 0, 8) . substr($charid, 8, 4) . substr($charid, 12, 4) . substr($charid, 16, 4) . substr($charid, 20, 12);
}

function create_uuid($prefix = ""){//可以指定前缀
    $str = md5(uniqid(mt_rand(), true));
    $uuid  = substr($str,0,8);
    $uuid .= substr($str,8,4);
    $uuid .= substr($str,12,4);
    $uuid .= substr($str,16,4);
    $uuid .= substr($str,20,12);
    return $prefix . $uuid;
}

function alert($msg, $url = NULL, $parent = false) {
    header("Content-type: text/html; charset=utf-8");
    $alert_msg = "alert('$msg');";
    if (empty($url)) {
        $gourl = 'history.go(-1);';
    } else {
        $gourl = ($parent ? 'parent' : 'window') . ".location.href = '{$url}'";
    }
    echo "<script>$alert_msg $gourl</script>";
    exit();
}